import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:month_picker_dialog/month_picker_dialog.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/report/core_report_detail_page.dart';
import 'package:yuan_hang_app/views/report/model/core_rate_report.dart';

import '../../http/api.dart';
import '../../res/w_colors.dart';
import '../../res/w_dimens.dart';
import '../../utils/common_utils.dart';
import '../../utils/string_utils.dart';
import '../../widget/custom_search.dart';
import '../../widget/sort_content.dart';
import '../../widget/w_line.dart';
import '../../widget/w_list_view.dart';
import '../../widget/w_popup_window.dart';
import '../../widget/w_text.dart';
import '../home/view/leads/widget/common_date.dart';

class CoreReportPage extends StatefulWidget {
  const CoreReportPage({super.key});

  @override
  BaseState<CoreReportPage> createState() => CoreReportPageState();
}

class CoreReportPageState extends BaseState<CoreReportPage> {
  Map sortParams = {};
  WListViewState? listState;
  List<CoreRateReport> dataList = [];

  Map<String, dynamic> queryParams = {
    "pageNum": 1,
    "limit": 20,
  };

  String initDateStr =
      DateUtil.formatDate(DateTime.now(), format: DateFormats.y_mo);

  @override
  void initState() {
    super.initState();
    queryParams["atYear"] = DateTime.now().year;
    queryParams["atMonth"] = DateTime.now().month;
  }

  void fetchDataList() {
    HttpUtils()
        .get(Api.getCoreReportList, queryParams: queryParams)
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data["records"] ?? [];
          List<CoreRateReport> list =
              data.map((item) => CoreRateReport.fromJson(item)).toList();
          listState?.onRefreshData(list, queryParams["pageNum"]);
          if (queryParams["pageNum"] == 1) {
            dataList.clear();
          }
          dataList.addAll(list);
        }
      } else {
        listState?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
      listState?.onFail(e);
    });
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "核心四率报表",
      child: Column(
        children: [
          CustomSearch(
            hintText: "直营店简称",
            onSortClick: () {
              WPopupWindow.showSort(
                  context: context,
                  sortType: SortType.CORE_RATE_REPORT,
                  sortParams: sortParams,
                  onSelected: (Map params) {
                    sortParams = params;
                    params.forEach((key, value) {
                      queryParams[key] = value;
                      if (queryParams.containsKey(key) && value == null) {
                        queryParams.remove(key);
                      }
                    });
                    showLoading();
                    fetchDataList();
                  });
            },
            onTextChange: (text) {
              queryParams["pageNum"] = 1;
              queryParams["dealerName"] = text;
              CommonUtils.antiShake(fetchDataList);
            },
          ),
          dateWidget(),
          Expanded(
              child: WListView(
            padding: EdgeInsets.only(top: 10.px),
            itemBuilder: _listItem,
            getDataList: (currentState, page) {
              listState = currentState;
              queryParams["pageNum"] = page;
              fetchDataList();
            },
          )),
        ],
      ),
    );
  }

  Widget _listItem(context, index, dataList) {
    CoreRateReport item = dataList[index];

    return GestureDetector(
      onTap: () => {
        RouteHelper.pushWidget(
            context,
            CoreReportDetailPage(
              dealerCode: item.dealerCode,
              atYear: queryParams["atYear"].toString(),
              atMonth: queryParams["atMonth"].toString(),
            )).then((_) {
          queryParams["pageNum"] = 1;
          fetchDataList();
        })
      },
      child: Container(
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
              color: WColors.CDFEFFB,
              offset: const Offset(0, 1),
              blurRadius: 3.px)
        ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
        margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        padding: EdgeInsets.only(bottom: 10.px),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 10.px),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    color: WColors.primaryColor,
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.px),
                      child: WText(
                        item.dealerName ?? "",
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: WDimens.tsLarge,
                            color: WColors.mainTextColor,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 5.px,
              ),
              // WLine(
              //   height: 1.px,
              //   marginTop: 6.px,
              //   marginBottom: 6.px,
              // ),
              _itemRow("", "完成率", "目标率"),
              _itemRow(
                  "总线索目标完成率", "${item.clueRate}", "${item.clueTargetRate}"),
              _itemRow("线索有效率", "${item.validRate}", "${item.validTargetRate}"),
              _itemRow(
                  "有效线索到店率", "${item.inshopRate}", "${item.inshopTargetRate}"),
              _itemRow("到店试驾率", "${item.testDriveRate}",
                  "${item.testDriveTargetRate}"),
              _itemRow("到店成交率", "${item.saleRate}", "${item.saleTargetRate}", isLast: true),
            ]),
      ),
    );
  }

  Widget _itemRow(title, fRate, tRate, {bool isLast = false}) {
    BoxDecoration leftDecoration = BoxDecoration(
        border: Border(
            left: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    BoxDecoration rightDecoration = BoxDecoration(
        border: Border(
            left: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            top: BorderSide(color: WColors.CCCCCCC, width: 1.px),
            right: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    BoxDecoration midDecoration = BoxDecoration(
        border: Border(top: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    if (isLast) {
      leftDecoration = BoxDecoration(
          border: Border.all(color: WColors.CCCCCCC, width: 1.px));
      rightDecoration = BoxDecoration(
          border: Border.all(color: WColors.CCCCCCC, width: 1.px));
      midDecoration = BoxDecoration(
          border: Border.symmetric(horizontal: BorderSide(color: WColors.CCCCCCC, width: 1.px)));
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 5.px),
      child: Row(
        children: [
          Expanded(
            flex: 3,
            child: Container(
              padding: EdgeInsets.only(left: 5.px),
              decoration: leftDecoration,
              child: WText(
                title,
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              alignment: Alignment.center,
              decoration: midDecoration,
              child: WText(
                fRate,
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Container(
              alignment: Alignment.center,
              decoration: rightDecoration,
              child: WText(
                tRate,
                style: TextStyle(
                    fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget dateWidget() {
    return GestureDetector(
      onTap: () {
        _showDatePickerForDate(initDateStr).then((dateTime) {
          setState(() {
            if (dateTime != null) {
              queryParams["atYear"] = dateTime.year;
              queryParams["atMonth"] = dateTime.month;
              initDateStr =
                  DateUtil.formatDate(dateTime, format: DateFormats.y_mo);
              queryParams["pageNum"] = 1;
              showLoading();
              fetchDataList();
            }
          });
        });
      },
      child: Container(
        height: 36.px,
        color: Colors.white,
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 5.px),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "images/ic_calendar.png",
              width: 20.px,
            ),
            SizedBox(
              width: 5.px,
            ),
            Container(
                width: 60.px,
                child: WText(initDateStr,
                    style: TextStyle(
                        fontSize: WDimens.tsMedium,
                        color: WColors.mainTextColor))),
          ],
        ),
      ),
    );
  }

  Future _showDatePickerForDate(selectDate) async {
    selectDate = selectDate + "-01";
    return showMonthPicker(
      context: context,
      firstDate: DateTime(DateTime.now().year - 10, 1),
      lastDate: DateTime(DateTime.now().year + 10, 12),
      initialDate: DateTime.parse(selectDate),
      confirmWidget: const Text('确认'),
      cancelWidget: const Text('取消'),
      monthPickerDialogSettings: const MonthPickerDialogSettings(
          dialogSettings: PickerDialogSettings(dialogRoundedCornersRadius: 10),
          headerSettings: PickerHeaderSettings(
            headerCurrentPageTextStyle:
                TextStyle(fontSize: 14, color: WColors.white),
            headerBackgroundColor: WColors.primaryColor,
            headerSelectedIntervalTextStyle:
                TextStyle(fontSize: 16, color: WColors.white),
          ),
          buttonsSettings: PickerButtonsSettings(
              selectedDateRadius: 8,
              selectedMonthBackgroundColor: WColors.primaryColor)),
    );
  }
}
